package gui;

import java.awt.BorderLayout;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.util.ArrayList;
import java.util.GregorianCalendar;
import java.util.Iterator;
import java.util.Scanner;

import javax.swing.BoxLayout;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.ScrollPaneConstants;

import main.Conference;
import main.Roles;
import main.User;


/**
 * StartFrame is the GUI for the starting screen
 * of the Manuview program.
 * 
 * Holly helped simplify populateRoles
 * Cris cleaned up and reviewed code
 * 
 * @author Daniel Anderson - Back End
 * @author Amandeep - GUI
 * @version 12/3
 */
public class StartFrame extends JFrame{
	
	/**
	 * 
	 */
	private static final long serialVersionUID = 3870069593790562678L;
	//GUI Stuff
	private JFrame my_frame;
	private JPanel my_user_panel;
	private JPanel my_conf_panel;
	private JPanel my_role_panel;
	private JButton my_go_button;
	
	//Data Stuff
	private ArrayList<User> my_users;
	private ArrayList<Conference> my_confs;
	private User my_current_user;
	private Conference my_current_conf;
	private Roles my_current_role;
	
	/**
	 * Constructor for StartFrame
	 * Initializes/Loads Users and Conferences.
	 */
	public StartFrame() {
		super();
		my_frame = new JFrame("Manuview Selection");
		my_users = new ArrayList<User>();
		my_confs = new ArrayList<Conference>();
		my_go_button = new JButton("Continue");
		my_user_panel = new JPanel();
		my_role_panel = new JPanel();
		my_conf_panel = new JPanel();
		try {
			loadConferences();
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		}
		loadUsers();
	}//end StartFrame constr
	
	/**
	 * Creates and displays the GUI.
	 * Must be called after creating a StartFrame object.
	 */
	public void start() {
		//setup
		my_frame.setLayout(new BorderLayout());
		my_frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		my_frame.setSize(800,600);
		my_frame.setResizable(false);
		
		//User Selection Window (left)
		JScrollPane scroll1 = new JScrollPane(my_user_panel);
		my_user_panel.setLayout(new BoxLayout(my_user_panel, BoxLayout.Y_AXIS));
		scroll1.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS);
		scroll1.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER);
		
		//Conference Selection Window (middle)
		my_conf_panel.setLayout(new BoxLayout(my_conf_panel, BoxLayout.Y_AXIS));
		JScrollPane scroll2 = new JScrollPane(my_conf_panel);
		scroll2.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS);
		scroll2.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER);
		
		//Role Selection Window (right)
		JScrollPane scroll3 = new JScrollPane(my_role_panel);
		my_role_panel.setLayout(new BoxLayout(my_role_panel, BoxLayout.Y_AXIS));
		scroll3.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS);
		scroll3.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER);

		//Set up go button
		my_go_button.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
		        switch (my_current_role) {
		            case AUTHOR:
						final AuthorSubmitsFrame nextwindow = 
							new AuthorSubmitsFrame(my_current_user, 
									my_current_conf);
						nextwindow.start();
						my_frame.dispose();
		            	break;
		            case PROGRAMCHAIR:
		            	final PCViewsFrame nextwin = new PCViewsFrame(my_current_conf);
		            	//System.out.println("PROGRAMCHAIR");
						nextwin.start();
						my_frame.dispose();
		            	break;
		            case REVIEWER:
		            	final  ReviewSubmitsFrame revwin = 
		            		new ReviewSubmitsFrame (my_current_user, my_current_conf);
		            	//System.out.println("REVIEWER");
						revwin.start();
						my_frame.dispose();
		            	break;
		            default: 
		            	System.out.println("DEFAULT");
		            	break;
		        }
		        


				/*
				System.out.println("Selected User: " + 
						my_current_user.getName() + " " + 
						my_current_user.getID());
				System.out.println("Selected Conference: " + 
						my_current_conf.getConfName());
				System.out.println("Selected Role: " + my_current_role);
				*/
			}
		});
		my_go_button.setEnabled(false);
		
		//add the panels
		JPanel top = new JPanel();
		top.setLayout(new GridLayout());
		top.add(scroll1);
		top.add(scroll2);
		top.add(scroll3);
		my_frame.add(top, BorderLayout.CENTER);
		my_frame.add(my_go_button, BorderLayout.PAGE_END);
		populateUserPanel();
	    my_frame.setVisible(true);
	}//end of start
	

	/**
	 * Loads the users from the list of conferences
	 * 
	 * @author Cristopher
	 */
	private void loadUsers() {
		for(int i = 0; i < my_confs.size(); i++) {
			for(int j = 0; j < my_confs.get(i).getUsers().size(); j++){
				if(!my_users.contains(my_confs.get(i).getUsers().get(j))){
					my_users.add(my_confs.get(i).getUsers().get(j));
				}
			}
		}
	}//end loadUsers
	
	/**
	 * Loads the list of conference object specified in the config.txt file
	 * 
	 * @author Cristopher
	 * 
	 * @throws FileNotFoundException thrown if config.txt file is not provided
	 */
	private void loadConferences() throws FileNotFoundException {
		File config = new File("config.txt");
		Scanner scan = new Scanner(new FileReader(config));
		String directory = scan.nextLine();
		while(scan.hasNextLine()){
			Conference temp = restoreConf(new File(directory+scan.nextLine()+".ser"));
			temp.setDirectory(directory);
			my_confs.add(temp);
		}
	}//end loadCOnferences
	
	/**
	 * Restores a serialized conference object
	 * 
	 * @author Cristopher
	 * 
	 * @param a_file name of the serialized file
	 * @return Restore conference object
	 */
	private Conference restoreConf(File a_file) {
		Conference localConf = null;
		try {
		  FileInputStream fis = new FileInputStream(a_file.getPath());
		  ObjectInputStream in = new ObjectInputStream(fis);
		  localConf = (Conference)in.readObject();
		  in.close();
		}
		catch(IOException ex){
	      ex.printStackTrace();
		}
		catch(ClassNotFoundException ex){
		  ex.printStackTrace();
		}
		return localConf;
	}
	
	//The populate methods look at the currently supplied User,
	//Conference, and Role data and determine what buttons will 
	//be added to the window. 
	private void populateUserPanel() {
		Iterator<User> iterator = my_users.iterator();
		while(iterator.hasNext()) {
			final User u = iterator.next();
			JButton button = new JButton(u.getName() + " " + u.getID());
			button.addActionListener(new ActionListener() {
				public void actionPerformed(ActionEvent e) {
					my_current_user = u;
					populateConfPanel();
				}
			});
			my_user_panel.add(button);
		}
	}//end populateUserPanel
	
	private void populateConfPanel() {
		my_conf_panel.removeAll();//clear old buttons
		my_role_panel.removeAll();//clear Role buttons
		Iterator<Conference> iterator = my_confs.iterator();
		while(iterator.hasNext()) {
			final Conference c = iterator.next();
			if(c.getUsers().contains(my_current_user)) {
				JButton button = new JButton(c.getConfName());
				button.addActionListener(new ActionListener() {
					public void actionPerformed(ActionEvent e) {
						my_current_conf = c;
						populateRolePanel();
					}
				});
				my_conf_panel.add(button);
			}
		}
		
		//clear any old selections
		my_current_conf = null;
		my_current_role = null;
		//Disable going to next window
		my_go_button.setEnabled(false);
		
		//update both the conf and role panel.
		my_conf_panel.revalidate();
		my_role_panel.revalidate();
		my_conf_panel.repaint();
		my_role_panel.repaint();
	}//end populateConfPanel
	
	private void populateRolePanel() {
		my_role_panel.removeAll();//clear Role buttons
		
		//Holly's Simplified Solution
		//Dan made a small change, that basically changes my_current_user
		//from the hollowed copy to the specific one inside the conference
		//that holds the manuscripts and what not.
		my_current_user = my_current_conf.getUsers().get(my_current_conf.getUsers().indexOf(my_current_user));
        Iterator<Roles> itr = my_current_user.getRoles().iterator();
        while (itr.hasNext()){
            final Roles aRole = itr.next();
            JButton aButton = new JButton(aRole.toString());
            aButton.addActionListener(new ActionListener() {
                public void actionPerformed(ActionEvent e) {
                    my_current_role = aRole;
                    my_go_button.setEnabled(true);
                }
            });            
            my_role_panel.add(aButton);
        }
        
		//clear any old selection
		my_current_role = null;
		//update both the conf and role panel.
		//revall updates items, repaint updates display
		my_role_panel.revalidate();
		my_role_panel.repaint();
	}//end populateRolePanel
}//end of StartFrame